const KoaRouter = require('koa-router')
const glob = require('glob')
const _ = require('lodash')
const { resolve } = require('path')
require('babel-polyfill');


const _symbolPrefix = Symbol('prefix')
const _routerMap = new Map()

const _normalizePath = path => path.startsWith('/') ? path : `/${path}`
const _normalizeArray = arr => _.isArray(arr) ? arr : [arr]

class Router {
    constructor(app, ctrlPath) {
        this.app = app
        this.ctrlPath = ctrlPath
        this.router = new KoaRouter()
    }
    init() {
        const { app, ctrlPath, router } = this
        glob.sync(resolve(ctrlPath, './*.js')).forEach(require)

        let routerPrefix, routerPath
        for (let [conf, controller] of _routerMap) {
            let { path, method } = conf
            routerPrefix = _normalizePath(conf.target[_symbolPrefix])
            controller = _normalizeArray(controller)
            routerPath = routerPrefix + path
            router[method](routerPath, ...controller)
        }
        app.use(router.routes())
        app.use(router.allowedMethods())
    }
}

const router = conf => (target, key, descriptor) => {
    console.log(conf)
    conf.path = _normalizePath(conf.path)
    _routerMap.set({ target, ...conf }, target[key])
}

const controller = path => target => (target.prototype[_symbolPrefix] = path)

const get = path => router({
    method: 'get',
    path
})

const post = path => router({
    method: 'post',
    path
})

const put = path => router({
    method: 'put',
    path
})

const del = path => router({
    method: 'del',
    path
})

const use = path => router({
    method: 'use',
    path
})

const all = path => router({
    method: 'all',
    path
})

module.exports = {
    Router,
    get,
    post,
    put,
    del,
    use,
    all,
    controller
}